<template>
    <div>
        <!--module2 goods-add page  商品发布页-->

        <el-form ref="form" :model="form" label-width="80px">
            <el-form-item label="商品分类">
                <el-col :span="6">
                    <el-select v-model="form.class1" placeholder="一级分类" @change="change1">
                        <!--<el-option label="区域一" value="shanghai"></el-option>-->
                        <el-option v-for="v in form.classList1" :key="v.id" :label="v.classification_name"
                                   :value="v.id"></el-option>
                    </el-select>
                </el-col>
                <el-col class="line" :span="0.5">-</el-col>
                <el-col :span="6">
                    <el-select v-model="form.class2" placeholder="二级分类" @change="change2">
                        <el-option v-for="v in form.classList2" :key="v.id" :label="v.classification_name"
                                   :value="v.id"></el-option>
                    </el-select>
                </el-col>
                <el-col class="line" :span="0.5">-</el-col>
                <el-col :span="6">
                    <el-select v-model="form.class3" placeholder="三级分类">
                        <el-option v-for="v in form.classList3" :key="v.id" :label="v.classification_name"
                                   :value="v.id"></el-option>
                    </el-select>
                </el-col>
            </el-form-item>
            <el-form-item label="商品名称">
                <el-input v-model="form.goods_name"></el-input>
            </el-form-item>
            <el-form-item label="商品图片">
                <div>
                    <uploadList @upload="upCallback"></uploadList>
                    <!--<el-button><i class="el-icon-upload2"></i> 上传头像</el-button>-->
                </div>
                <div>
                    <img v-for="v in form.imgList"
                         :src="'https://dlhz.oss-cn-beijing.aliyuncs.com/'+(v.rename||v.img_url)+'?x-oss-process=image/resize,w_80,h_80'"
                         alt=""
                         style="display:inline-block;vertical-align:bottom;width: 80px;height: 80px;border: 1px solid #eee;">
                </div>
            </el-form-item>
            <el-form-item label="规格/价格">
                <i style="color: red;font-size: 0.5rem;">规格填写示例：长5-10CM，去皮，500KG/包...（注意：规格之间用逗号隔开）</i>
                <template v-for="v in form.standard">
                    <el-input type="textarea" v-model="v.norm" placeholder="输入规格"></el-input>
                    <el-input v-model="v.unit" placeholder="输入单位（必填）"></el-input>
                    <el-input v-model="v.price" placeholder="输入价格（必填）"></el-input>
                    <div style="height: 0.5rem;"></div>
                </template>
                <i class="el-icon-lx-roundadd standardAdd" @click="standardAdd"></i>
            </el-form-item>

            <el-form-item>
                <el-button type="primary" @click="addProduct('0')">{{uid?'提交':'添加'}}</el-button>
                <el-button type="success" @click="addProduct('1')" v-if="!uid">添加并发布</el-button>
            </el-form-item>
        </el-form>
    </div>
</template>

<script>
    import uploadList from '@/components/common/UploadList'

    export default {
        components: {
            uploadList,
        },
        data() {
            return {
                form: {
                    goods_name: '',
                    classList1: [],
                    class1: '',
                    classList2: [],
                    class2: '',
                    classList3: [],
                    class3: '',
                    imgList: [],

                    standard: [
                        {
                            norm: '',
                            unit: '',
                            price: '',
                        },
                    ],
                    type: [],
                    resource: '',
                    desc: ''
                }
            }
        },
        props: ['uid'],
        methods: {
            loadopen() {
                this.loading = this.$loading({
                    lock: true,
                    text: 'Loading',
                    spinner: 'el-icon-loading',
                    background: 'rgba(0, 0, 0, 0.2)'
                });
                setTimeout(() => {
                    this.loading.close();
                }, 5000);
            },
            loadclose() {
                this.loading.close();
            },
            // 获取一级
            getClass1() {
                this.loadopen();
                this.config.post('/supply/goodsClassification/find', {}).then(res => {
                    this.loadclose();
                    if (res.data.code === '0') {
                        this.form.classList1 = res.data.list;
                    } else {
                        this.$message.error(this.config.handleError(res.data));
                    }
                })
            },
            // 获取二级
            change1() {
                this.loadopen();
                this.config.post('/supply/goodsClassification/findByPid', {pid: this.form.class1}).then(res => {
                    this.loadclose();
                    if (res.data.code === '0') {
                        this.form.classList2 = res.data.list;
                        this.form.class2 = '';
                        this.form.class3 = '';
                    } else {
                        this.$message.error(this.config.handleError(res.data));
                    }
                })
            },
            // 获取三级
            change2() {
                this.loadopen();
                this.config.post('/supply/goodsClassification/findByPid', {pid: this.form.class2}).then(res => {
                    this.loadclose();
                    if (res.data.code === '0') {
                        this.form.classList3 = res.data.list;
                        this.form.class3 = '';
                    } else {
                        this.$message.error(this.config.handleError(res.data));
                    }
                })
            },
            // 增加规格
            standardAdd() {
                this.form.standard.push({})
            },
            // 获取商品信息
            getInfo() {
                if (!this.uid) {
                    return;
                }
                this.loadopen();
                this.config.get('/supply/goods/findById', {id: this.uid}).then(res => {
                    this.loadclose();
                    if (res.data.code === '0') {
                        // console.log(res.data, '获取角色信息');
                        this.form.goods_name = res.data.goods.goods_name;
                        // this.form.class1 = res.data.goods.classification_id;
                        this.form.imgList = res.data.goods.imgList;
                        this.form.standard = JSON.parse(res.data.goods.norms || "[]");
                        res.data.goods.classificationPidjson.forEach(item => {
                            if (item.floor === 0) {
                                this.form.class1 = item.id;
                                this.change1();
                            } else if (item.floor === 1) {
                                setTimeout(() => {
                                    this.form.class2 = item.id;
                                    this.change2();
                                }, 200);
                            } else if (item.floor === 2) {
                                setTimeout(() => {
                                    this.form.class3 = item.id;
                                }, 400)
                            }
                        })
                    } else {
                        this.$message.error(this.config.handleError(res.data));
                    }
                });
            },
            // 获取上传文件控件返回的地址
            upCallback(list) {
                // this.form.imgList = 'https://dlhz.oss-cn-beijing.aliyuncs.com/'+url;
                this.form.imgList = list;
            },
            validate() {
                if (!this.form.class1) {
                    this.$message.error('请选择商品分类');
                    return false;
                }
                if (!this.form.goods_name) {
                    this.$message.error('请填写商品名称');
                    return false;
                }
                return true;
            },
            // 添加商品
            addProduct(isIssue) {
                if (!this.validate()) return;
                let classId = this.form.class3 ? this.form.class3 : this.form.class2 ? this.form.class2 : this.form.class1;
                let sarr = [];
                this.form.standard.forEach(item => {
                    if (item.norm && item.unit && item.price) {
                        sarr.push(item);
                    }
                });
                let imgs = [];
                this.form.imgList.forEach(it => {
                    imgs.push(it.rename||it.img_url)
                });
                let obj = {
                    'goods.id': this.uid,
                    'goods.classification_id': classId, // 商品分类id 取最后一级的分类id
                    'goods.goods_name': this.form.goods_name, // 商品名称
                    'goods.norms': JSON.stringify(sarr), // 商品规格json
                    'audit': isIssue === '0' ? '0' : '1', // 商品规格json
                    'imgs': imgs.join(','), // 商品图片json
                };
                let url = this.uid ? '/supply/goods/edit' : '/supply/goods/add';
                this.loadopen();
                this.config.post(url, obj).then(res => {
                    this.loadclose();
                    if (res.data.code === '0') {
                        this.$message.success(res.data.message);
                    } else {
                        this.$message.error(this.config.handleError(res.data));
                    }
                    this.$emit('done', '');
                })
            },
        },
        mounted() {
            this.getClass1();
        }
    }
</script>

<style scoped>
    .standardAdd {
        font-size: 1.5rem;
        vertical-align: middle;
        color: #2d8cf0
    }
</style>
